package com.chzc.fm.duotin.ui.home;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.adapter.listview.HomePlay1LastCommentListViewAdapter;
import com.chzc.fm.duotin.bean.home.AlbumBean;
import com.chzc.fm.duotin.bean.home.ContentBean;
import com.chzc.fm.duotin.bean.home.HomePlayer1Bean;
import com.chzc.fm.duotin.bean.home.LastCommandDataList;
import com.chzc.fm.duotin.bean.home.LatestCommentsBean;
import com.chzc.fm.duotin.bean.home.PodcastBean;
import com.chzc.fm.duotin.ui.home.utils.HomeUtils;
import com.chzc.fm.duotin.ui.home.utils.IPlayerServer;
import com.chzc.fm.duotin.ui.home.utils.JumpManager;
import com.chzc.fm.duotin.ui.home.utils.PlayerServerEventNotify;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.FastBlur;
import com.chzc.fm.duotin.utils.FileUtils;
import com.chzc.fm.duotin.utils.HttpUtil;
import com.chzc.fm.duotin.utils.ImageUtil;
import com.chzc.fm.duotin.utils.LogUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;




/**
 * Created by Administrator on 2016/6/27.
 */
public class Player1Activity extends AppCompatActivity {

    //返回按钮
    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.ivlist)
    ImageView ivlist;
    @Bind(R.id.ivShare)
    ImageView ivShare;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.ivTops)
    RelativeLayout ivTop;
    @Bind(R.id.ivPlay)
    ImageView ivPlay;
    @Bind(R.id.skBar)
    SeekBar skBar;
    @Bind(R.id.ivKnock)
    ImageView ivKnock;
    @Bind(R.id.ivComment)
    ImageView ivComment;
    @Bind(R.id.something15)
    ImageView something15;
    @Bind(R.id.lastMusic)
    ImageView lastMusic;
    @Bind(R.id.players)
    ImageView players;
    @Bind(R.id.nextMusic)
    ImageView nextMusic;
    @Bind(R.id.something30)
    ImageView something30;
    @Bind(R.id.ivManual)
    LinearLayout ivManual;
    @Bind(R.id.tvArcoh)
    TextView tvArcoh;
    @Bind(R.id.line)
    View line;
    @Bind(R.id.rlManual)
    RelativeLayout rlManual;
    @Bind(R.id.ivHeader)
    ImageView ivHeader;
    @Bind(R.id.rlShow)
    RelativeLayout rlShow;
    @Bind(R.id.tvMore)
    TextView tvMore;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    private String urlID;
        //背景图片
    private ImageView ivBackground ;
    //面板图片
    private ImageView ivAlbaum;
    //下载界面的id
    private String albumId;
    //评论列表
    private ListView listView;

    //跑马灯文字
    private TextView tvContents;

    private String mp3Url;
    //声明服务
    private IPlayerServer baService;
    private Player1PlayServer.MedaiPlayMessage mediaPlayMessage;
    //更新进度条
    private Timer timer = new Timer();
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            //在缓冲好后采取获取才能避免报错
            if(isPlayPrepare){
                //
                //
                // 执行了吗
                mediaPlayMessage = baService.getMessage();
                int currTime = mediaPlayMessage.currentTime;//当前时间
                int allTime = mediaPlayMessage.duration;//总时长
                final int progress = skBar.getMax()*currTime/allTime;

                //Log.e("msg"," = 播放的时刻"+currTime+" ---- "+allTime);
                //在主线程中更新进度
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        skBar.setProgress(progress);
                    }
                });
            }
        }
    };
    private boolean isPlaying = false;
    //判断是否需要播放还是暂停

    private int play = 2;
    private boolean isPlayPrepare = false;
    private HomePlay1LastCommentListViewAdapter adapter;
    private String id;//主播信息

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_palyer1);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        //背景图片
        ivBackground = (ImageView) findViewById(R.id.ivBackground);

        //设置内容
        tvContents = (TextView) findViewById(R.id.tvContents);
        //设置评论列表
        listView = (ListView) findViewById(R.id.lv_comment);
        listView.setEmptyView(findViewById(R.id.defaults));
        adapter = new HomePlay1LastCommentListViewAdapter(Player1Activity.this);
        listView.setAdapter(adapter);
        skBar = (SeekBar) findViewById(R.id.skBar);
        skBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
           }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
              //  int max = seekBar.getMax();
                //Player1PlayServer.rate = progress/100;
                baService.setProgress(progress);

            }
        });

        //旋转动画
        rotate();
        initData();

    }

    @Subscribe
    public void onEventMainThread(PlayerServerEventNotify notify){
        //这里有执行吗
      //  Log.e("msg","这里执行了");
        this.isPlaying = notify.isPlaying();
        boolean hello = notify.isPlayPrePara();
        this.isPlayPrepare = true;
        timer.schedule(task,500,500);
    }

    private void initData() {
        urlID = getIntent().getStringExtra("urlID");
        LogUtil.e("Player1ActivityurlID"+urlID);
        //获取从播放页面url中的数据
        HomeUtils.getPlayerMessage(new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                //获取json中的数据并将之呈现在屏幕上
                try {

                    //将数据转换为unicode
                    String unicodeResult = object.toString();

                    JSONObject root = new JSONObject(unicodeResult);
                    String message = root.getString("error_msg");
                    if ("SUCCESS".equals(message)) {
                        JSONObject data = root.getJSONObject("data");
                        HomePlayer1Bean result = HomePlayer1Bean.objectFromData(data.toString());
                        //添加内容
                        AlbumBean album = result.getAlbum();
                        final String url = album.getImage_url();//背景图片地址
                        setBackgroundByUrl(url);
                        //设置头像
                        PodcastBean podcast = result.getPodcast();
                        String podcastImage_url = podcast.getImage_url();
                        if (podcastImage_url!=null){

                            setHeaderImageResource(podcastImage_url);
                        }
                        //添加跑马灯文字
                        ContentBean content = result.getContent();
                        albumId = content.getId();
                        String text = content.getTitle();
                        tvContents.setText(text);
                        //播放
                        mp3Url = content.getAudio_32_url();
                        //开启并绑定服务，用服务来播放音乐
                        Log.e("mp3Url"," "+mp3Url);
                        startAudioService();

                        //显示最后一个评论人的信息
                        LatestCommentsBean lastcomment = result.getLatest_comments();
                        if (lastcomment.getData_list()!=null) {
                            //将最后一条评论显示出来
                            List<LastCommandDataList> lastDataList = lastcomment.getData_list();
                            setCommentList(lastDataList);
                        }


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(String msg) {

            }
        }, urlID);

    }

    private void setCommentList(List<LastCommandDataList> lastDataList) {
            //若有评论数据则显示
            adapter.setmCommendList(lastDataList);
            adapter.notifyDataSetChanged();
           setListViewHeightBasedOnChildren(listView);//有多少项就显示多少宽高

    }

    private void startAudioService() {
        Intent intent = new Intent(Player1Activity.this,Player1PlayServer.class);
        intent.putExtra("mp3url",mp3Url);
        startService(intent);
        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                baService = (IPlayerServer)service;
                mediaPlayMessage = baService.getMessage();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

                baService=null;
            }
        }, Context.BIND_AUTO_CREATE);
    }


    private void rotate() {
        //播放界面的动画效果
        Animation animation = AnimationUtils.loadAnimation(Player1Activity.this, R.anim.rotate);

        Drawable picture =getResources().getDrawable(R.drawable.ic_track_loading);
        players.setImageDrawable(picture);
        players.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                    //判断是否可以开始播放如果是则停止动画
                    if (isPlayPrepare){

                        players.setImageDrawable(getResources().getDrawable(R.drawable.ic_track_playing_nor));

                        //开始播放音乐
                        PlayerServerEventNotify pauseNotify = new PlayerServerEventNotify();
                        pauseNotify.setPlaying(false);
                        EventBus.getDefault().post(pauseNotify);
                        //
                        //players.setSelected(true);
                        Log.e("ss","这里又是什么情况");

                    }else{

                        players.startAnimation(animation);
                    }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void setHeaderImageResource(final String podcastImage_url) {
        //设置圆形图片
        ImageLoader.getInstance().displayImage(podcastImage_url,ivHeader, ImageUtil.getCircleOptions());
    }

    private void setBackgroundByUrl(final String url) {
        new DuotinTask(new DuotinTask.IRequest() {
            @Override
            public Object doRequest() {
                File file =   HttpUtil.download(url, FileUtils.DIR_IMAGE,FileUtils.getFileNameByHashCode(url),null);

                return file;
            }
        }, new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                File file = (File) object;
                //下载背景图片
                Bitmap background = BitmapFactory.decodeFile(file.getAbsolutePath());
                //将背景图片进行模糊处理
                if(background!=null){
                    LogUtil.e("图片不为空");
                }
               FastBlur.blur(Player1Activity.this,background,ivBackground);

                ivPlay.setImageBitmap(background);
            }

            @Override
            public void error(String msg) {

            }
        }).execute();
    }


    @OnClick({R.id.ivBackground, R.id.ivBack, R.id.ivlist, R.id.ivShare, R.id.tvTitle, R.id.ivTops, R.id.ivPlay, R.id.skBar, R.id.ivKnock, R.id.ivComment, R.id.something15, R.id.lastMusic, R.id.players, R.id.nextMusic, R.id.something30, R.id.ivManual, R.id.tvArcoh, R.id.line, R.id.rlManual, R.id.ivHeader, R.id.rlShow, R.id.tvMore, R.id.scrollView})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBackground:
                break;
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivlist:

                JumpManager.jumpPlay1PlyList(this,albumId);

                break;
            case R.id.ivShare:
                break;
            case R.id.tvTitle:
                break;
            case R.id.ivTops:
                break;
            case R.id.ivPlay:
                break;
            case R.id.skBar:
                break;
            case R.id.ivKnock:
                //打开定时开关页面
                JumpManager.jumpPlay1DingShi(this);
                break;
            case R.id.ivComment:

                //打开主播信息页面
                JumpManager.jumpPlay1MsgPlyList(this,id);

                break;
            case R.id.something15:
                break;
            case R.id.lastMusic:
                break;
            case R.id.players:
                //用于判断点击事件
                play++;

                if (play%2==0){

                    //点击暂停播放
                    players.setImageResource(R.drawable.ico_player_play_normal);
                    PlayerServerEventNotify pauseNotify = new PlayerServerEventNotify();
                    pauseNotify.setPlaying(true);
                    EventBus.getDefault().post(pauseNotify);

                }else{
                    //点击继续播放
                    players.setImageResource(R.drawable.ic_track_playing_nor);
                    PlayerServerEventNotify pauseNotify = new PlayerServerEventNotify();
                    pauseNotify.setPlaying(false);
                    EventBus.getDefault().post(pauseNotify);
                }

                break;
            case R.id.nextMusic:
                break;
            case R.id.something30:
                break;
            case R.id.ivManual:
                break;
            case R.id.tvArcoh:
                break;
            case R.id.line:
                break;
            case R.id.rlManual:
                break;
            case R.id.ivHeader:
                break;
            case R.id.rlShow:
                break;
            case R.id.tvMore:
                break;
            case R.id.scrollView:
                break;
        }
    }


    @Override

    protected  void onPause(){
        super.onPause();
        ivTop.setVisibility(View.GONE);
        scrollView.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {

        super.onResume();

        ivTop.setVisibility(View.VISIBLE);
        scrollView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        task.cancel();

    }
    //动态设置listview的宽高
    private void setListViewHeightBasedOnChildren(ListView listView){
        if(listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

}
